package org.brisling.innerMail.service;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.brisling.authorize.shiro.ShiroSecurityService;
import org.brisling.base.domain.ListDomain;
import org.brisling.base.domain.RetDomain;
import org.brisling.common.ConstSysParam;
import org.brisling.common.SysConfig;
import org.brisling.common.util.LongUtil;
import org.brisling.innerMail.domain.MailDetailDomain;
import org.brisling.innerMail.domain.MailInfoDomain;
import org.brisling.innerMail.repository.MailInfoRepo;
import org.brisling.sysman.domain.JobRole;
import org.brisling.sysman.domain.UploadFiles;
import org.brisling.sysman.domain.Users;
import org.brisling.sysman.queryService.QueryJobRoleService;
import org.brisling.sysman.queryService.QueryUploadService;
import org.brisling.sysman.queryService.QueryUserService;
import org.brisling.sysman.service.UploadService;
import org.brisling.sysman.service.base.BaseSysmanService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;


@RestController
@RequestMapping("/mailInfo")
/**
 * 用戶后台服務service
 * @Author : jackson wang
 * @Date   : 2015年6月8日 下午4:18:01
 * @version: 1.0
 */
public class MailInfoService extends BaseSysmanService<MailInfoDomain>{
	
	
	@Autowired
	private MailInfoRepo baseRepo;
	
	
	@Autowired
	private MailDetailService 	mailDetailService;
	
	@Autowired
	private UploadService 	uploadService;
	
	@Autowired
	private QueryUploadService 	qryUploadService;
	
	@Autowired
	private ShiroSecurityService shiroSecurityService;
	
	@Autowired
	private QueryJobRoleService qryJobRoleService;
	
	@Autowired
	private QueryUserService qryUserService;
	
	public MailInfoService(){
		this.moduleName = ConstSysParam.MODULE_MAIL_INFO;
		this.clazz = MailInfoDomain.class;
	}
	
	/**
	 * 获取业务主页面 
	 * @return
	 */
	@RequestMapping("/mainPage.action")
	public ModelAndView getMainPage(){
		return getBizMainPage();
	}
	
	/**
	 * 获取业务编辑页面
	 * @return
	 */
	@RequestMapping("/editPage.action")
	public ModelAndView getEditPage(){
		return getBizEditPage();
	}
	
	
	/**
	 * 分页查询邮件列表信息
	 * @param deptid
	 * @param page
	 * @param rows
	 * @param sort
	 * @return
	 */
	@RequestMapping("/getListDomain.action")
	public ListDomain<MailInfoDomain> getListDomain(
			@RequestParam(value="page",required=false) String page,
			@RequestParam(value="rows",required=false) String rows,
			@RequestParam(value="sort",required=false) String sort){
		
				
		return super.getPagedList(page, rows);
			
	}
	
	
	
	/**
	 * 分页查询用户列表页面
	 * @param deptid
	 * @param page
	 * @param rows
	 * @param sort
	 * @return
	 */
	@RequestMapping("/getList.action")
	public List<MailInfoDomain> getPagedListRows(
			@RequestParam(value="page",required=false) String page,
			@RequestParam(value="rows",required=false) String rows,
			@RequestParam(value="sort",required=false) String sort){
		
		
			return super.getAll(page,rows,getSort(sort));
			
	}
	
	/**
	 * 删除记录,单条或批量删除记录,id不为空，执行单条删除，id为空且ids不为空，执行批量删除
	 * @param id	待删除的单条记录id
	 * @param ids	待删除的多条记录id，以','分隔
	 * @return
	 */
	@RequestMapping("/del.action")
	public RetDomain delRow(@RequestParam(value="id",required=false) Long id,@RequestParam(value="ids",required=false) String ids){
		
		return super.delRows(id, ids);		 
	}
	
	/**
	 * 删除记录,单条或批量删除记录,id不为空，执行单条删除，id为空且ids不为空，执行批量删除
	 * @param id	待删除的单条记录id
	 * @param ids	待删除的多条记录id，以','分隔
	 * @return
	 */
	@RequestMapping("/flowDel.action")
	public RetDomain delFlowRow(@RequestParam(value="id",required=false) Long id,@RequestParam(value="ids",required=false) String ids){
		
		return delRow(id,ids);
		
	}
	
	
	/**
	 * 保存邮件信息
	 * @param id
	 */
	@RequestMapping("/save.action")
	public MailInfoDomain save(@RequestBody String body){
			
		MailInfoDomain beforeSavedDomain = bodyToObj(body, clazz);		
		
		MailInfoDomain savedDomain = null;
		
		//邮件明细
		MailDetailDomain detail = null;
		
		
		String userid = shiroSecurityService.getCurrentUserIdentify();
		Users u = SysConfig.getUsr(userid);
		beforeSavedDomain.setSendids(u.getId());
		beforeSavedDomain.setSendName(u.getName());
		beforeSavedDomain.setSendDeptid(u.getDeptid());
		beforeSavedDomain.setSendDeptName(u.getDeptName());
		
		//设置删除标志
		beforeSavedDomain.setIsDel("f");
		
		if(beforeSavedDomain.getCreateTime()==null){
			beforeSavedDomain.setCreateTime(new Date());
		}
		beforeSavedDomain.setModiDate(new Date());
		beforeSavedDomain.setCreater(u.getId());
		//根据id值判断是否新增操作
		if(beforeSavedDomain.getId()==null){			
			savedDomain= baseRepo.save(beforeSavedDomain);
			//更新附件，将临时id(tmpid)替换为保存后的id值
			uploadService.updateTmpid(beforeSavedDomain.getBizcode(),"'"+beforeSavedDomain.getTmpid()+"'",savedDomain.getId().toString());				
						
		}else{
			savedDomain= save(beforeSavedDomain);			
		}
		
		detail = new  	MailDetailDomain();
		detail.setId(savedDomain.getId());
		detail.setLob_contents(savedDomain.getLob_contents());
		mailDetailService.save(detail);
		return savedDomain;
	}	
	
	/**
	 * 保存邮件信息
	 * @param id
	 */	
	public MailInfoDomain saveArchive(MailInfoDomain beforeSavedDomain){
			
		
		if(beforeSavedDomain!=null){
			if(beforeSavedDomain.getBizno()==null || beforeSavedDomain.getBizno().trim().length()<=0){
				beforeSavedDomain.setBizno(super.generateBizno());
			}
		}
		
		//执行保存
		MailInfoDomain savedDomain= null ;
		
		
		//根据id值判断是否新增操作
		if(beforeSavedDomain.getId()==null){			
			savedDomain= save(beforeSavedDomain);
			//更新附件，将临时id(tmpid)替换为保存后的id值
			uploadService.updateTmpid(beforeSavedDomain.getBizcode(),"'"+beforeSavedDomain.getTmpid()+"'",savedDomain.getId().toString());				
					
		}else{
			savedDomain= save(beforeSavedDomain);
		}
		
		return savedDomain;
	}
	
	
	/**
	 * 更新邮件已读状态
	 * @param id	邮件id
	 * @return
	 */
	@RequestMapping("/updateReadStatus.action")
	public MailInfoDomain updateReadStatus(@RequestParam(value="id",required=false) Long id){
		
		MailInfoDomain ret = null;
		if(id!=null){			
			String sql = String.format(" update %1$s set isread = '2' where id = %2$d", this.moduleName,id);
			this.executeNativeDelOrUpdate(sql);			
			ret = this.getOne(id);
		}
		
		return ret;
	}	
	
	/**
	 * 更新邮件删除状态
	 * @param id	邮件id
	 * @param ids	邮件id集合字符串
	 * @param status	状态值(t:删除，f：未删除)
	 * @return
	 */
	@RequestMapping("/updateDelStatus.action")
	public RetDomain updateDelStatus(@RequestParam(value="id",required=false) Long id,
									 @RequestParam(value="ids",required=false) String ids,
									 @RequestParam(value="status",required=false) String status){
		
		RetDomain ret = null;
		
		String _ids = null;
		
		String _status = status==null?"t":status;
		if(id!=null){					
			_ids = id.toString();
		}else{
			_ids = ids;
		}		
		String sql = String.format(" update %1$s set isdel = '%2$s' where id in (%3$s)", this.moduleName,_status,_ids);
		this.executeNativeDelOrUpdate(sql);	
		return ret;
	}
	
	/**
	 * 保存并发送邮件信息
	 * @param id
	 */
	@RequestMapping("/send.action")
	public RetDomain saveSend(@RequestBody String body){
		
		RetDomain ret = new RetDomain();
		
		List<MailInfoDomain> mails = new ArrayList<MailInfoDomain>();
		
		MailInfoDomain m = this.bodyToObj(body, clazz);
		
		
		//获取当前附件信息
		List<UploadFiles> archivelists = this.getArchive(m);
		
		//转发标志判断
		if(m!=null && m.getReWrite()!=null){
			//转发邮件，id值清空
			m.setId(null);
		}
		//生成发件记录
		String userid = shiroSecurityService.getCurrentUserIdentify();
		Users u = SysConfig.getUsr(userid);
		m.setSendids(u.getId());
		m.setSendName(u.getName());
		m.setSendDeptid(u.getDeptid());
		m.setSendDeptName(u.getDeptName());
		if(m.getCreateTime()==null){
			m.setCreateTime(new Date());
		}
		m.setModiDate(new Date());
		m.setCreater(u.getId());
		
		//设置邮件已发送状态
		m.setStatus("4");
		
		//设置删除标志
		m.setIsDel("f");
		//将发件记录存入待保存列表
		mails.add(m);
		
		//临时存储邮件内容
		String _contents = m.getLob_contents();
		//根据接收邮件人员生成收件信息
		
		List<MailInfoDomain> recives = this.getReciveInfo(m);
		mails.addAll(recives);
		
		//保存邮件集合mails
		Iterable<MailInfoDomain> savedMail = baseRepo.save(mails);
		
		//保存邮件内容
		if( mails!=null && mails.size()>0 ){
			//保存邮件内容
			List<MailDetailDomain> details = this.generateDetail(mails, _contents);			
			if(details!=null){
				mailDetailService.save(details);
			}			
		}
		
		//保存邮件附件信息
		if(  (archivelists!=null) && (archivelists.size()>0) ){			
			
			//根据邮件集合及附件集合，生成并保存附件信息
			List<UploadFiles> newArchives = this.generateArchiveList(savedMail, archivelists);
			uploadService.saveList(newArchives);
		}
		return ret;
	}
	/**
	 * 保存收件记录
	 * @param id
	 */
	
	public RetDomain saveRecive(MailInfoDomain de){
		RetDomain domain = new RetDomain();
		if(de!=null){
			//获取业务编码
			String id = de.getId()==null?de.getTmpid():de.getId().toString();
			if(id!=null){
				//获取收件人
				Map<String,String> uMap = this.getReciveUser(de);
				if(uMap!=null && uMap.size()>0){
					
					
					UploadFiles uf =qryUploadService.getOneByField("bizno", id);
					
					for(String ukey:uMap.keySet()){
						MailInfoDomain eu = null;
						try {
							eu = (MailInfoDomain) BeanUtils.cloneBean(de);
						} catch (IllegalAccessException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (InstantiationException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (InvocationTargetException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (NoSuchMethodException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						
						eu.setId(null);
						eu.setReciveid(LongUtil.getLongValue(ukey,null));
						eu.setReciveName(SysConfig.getUsr(ukey).getName());
						eu = saveArchive(eu);
						
						
						if(uf!=null && uf.getId()!=null){
							UploadFiles newuf = new UploadFiles();
							newuf.setBizcode(eu.getBizcode());
							newuf.setBizno(eu.getId().toString());
							newuf.setFilename(uf.getFilename());
							newuf.setSavedFileName(uf.getSavedFileName());
							newuf.setFiletype(uf.getFiletype());
							uploadService.save(newuf);
						}
					}
				}
			}
		}
		

		domain.setSuccessMsg("success");
		return domain;
	}	
	
	/**
	 * 获取
	 * @return
	 */
	private Map<String,String> getReciveUser(MailInfoDomain m){
		
		Map<String,String> retMap = new HashMap<String,String> ();
		if(null!=m){
			Map<Long,Long> uMap = new HashMap<Long,Long>();
			//根据分组查找用户
			if(m.getReciveGroupids()!=null && m.getReciveGroupids().trim().length()>0){
				//添加分组查询用户方法参数
				Map<String,String> map = new HashMap<String,String>();
				map.put("jobcode_in", m.getReciveGroupids());
				
				//查询分组
				List<JobRole> lists = qryJobRoleService.getList(map);
				
				//判断分组用户查询结果
				if(lists!=null){
					for(JobRole j:lists){
						//循环添加收件人
						retMap.put(j.getUserid(), j.getUserid());
					}
				}
			}
			
			//添加直接选择人员信息
			if(m.getReciveUserids()!=null && m.getReciveUserids().trim().length()>0){
				String[] ids = m.getReciveUserids().split(",");
				for(String id:ids){
					retMap.put(id, id);
				}
			}
		}
		
		return retMap;
	}
	
	/*
	 * 获取收件记录
	 */
	private List<MailInfoDomain> getReciveInfo(MailInfoDomain m){
		List<MailInfoDomain> ret = new ArrayList<MailInfoDomain>();
		
		//获取收件人集合
		Map<String,String> uMap = this.getReciveUser(m);
		
		//获取发件人信息
		
		//迭代收件人集合
		for(String uid:uMap.keySet()){
			try {
				//复制邮件信息
				MailInfoDomain newMail = (MailInfoDomain) BeanUtils.cloneBean(m);
				
				
				Users u = qryUserService.getOne(LongUtil.getLongValue(uid, null));
				//Users u = SysConfig.getUsr(uid);
				
				if(null != u){
					//清除原有id值
					newMail.setId(null);
					
					//设置收件人信息
					newMail.setReciveid(u.getId());
					newMail.setReciveName(u.getName());
					newMail.setReciveDeptid(u.getDeptid());
					newMail.setReciveDeptname(u.getDeptName());
					
					//设置邮件收件标记
					newMail.setStatus("3");
					newMail.setIsRead("1");
					
					
					ret.add(newMail);
				}
				
			} catch (IllegalAccessException | InstantiationException | InvocationTargetException
					| NoSuchMethodException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return ret;
	}
	
	/*
	 * 获取附件信息
	 */
	private List<UploadFiles> getArchive(MailInfoDomain m){
		List<UploadFiles> lists = new ArrayList<UploadFiles>();
		if(null != m ){
			//获取业务记录id或临时id
			String id = m.getId()==null?m.getTmpid():m.getId().toString();
			
			//判断参数有效性
			if( (id!=null) && (m.getBizcode()!=null) ){
				Map<String,String> map = new HashMap<String,String> ();
				map.put("bizno_in", "'"+id+"'");
				map.put("bizcode", m.getBizcode());
				lists = qryUploadService.getList(map);
			}
		}		
		return lists;
	}
	
	/*
	 * 根据保存后的邮件集合，生成附件集合
	 */
	private List<UploadFiles> generateArchiveList(Iterable<MailInfoDomain> mails,List<UploadFiles> archivelists){
		List<UploadFiles> ret = new ArrayList<UploadFiles>();
		
		if( (mails!=null) && (archivelists!=null) ){
			//迭代邮件集合
			for(MailInfoDomain m:mails){
				String bizno = m.getId().toString();
				
				//迭代附件集合
				for(UploadFiles u:archivelists){
					
					try {
						//复制附件记录
						UploadFiles newArch = (UploadFiles) BeanUtils.cloneBean(u);
						
						//修改业务id
						newArch.setBizno(bizno);
						
						//清除原有id
						newArch.setId(null);
						//增加到附件集合中
						ret.add(newArch);
					} catch (IllegalAccessException | InstantiationException | InvocationTargetException
							| NoSuchMethodException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}
		
		return ret;
	}

	//生成邮件明细内容
	
	private List<MailDetailDomain> generateDetail(List<MailInfoDomain> mails,String contents){
		
		List<MailDetailDomain> details = null;
		if(mails!=null){
			details = new ArrayList<MailDetailDomain>();
			for(MailInfoDomain m:mails){
				MailDetailDomain d = new MailDetailDomain();
				d.setId(m.getId());
				d.setLob_contents(contents);
				details.add(d);
			}
		}
		
		return details;
	}
}
